<!DOCTYPE html>
<html>

<head>
    <title>Table 示例</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
    <table id="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>邮箱</th>
            </tr>
        </thead>
        <tbody>
            <!-- 数据将被动态插入到这里 -->
        </tbody>
    </table>
    <button id="export-btn">导出表格数据为CSV</button>
    <script>
        $(document).ready(function () {
            fetchData();
            $("#export-btn").click(exportTableToCSV);
        });

        function fetchData() {
            $.ajax({
                url: 'https://jsonplaceholder.typicode.com/users', // 示例接口
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    renderTable(data);
                    console.log(data, "data");
                },
                error: function (error) {
                    console.error('数据加载失败', error);
                }
            });
        }

        function renderTable(data) {
            var rows = '';
            $.each(data, function (index, item) {
                rows += '<tr>' +
                    '<td>' + item.id + '</td>' +
                    '<td>' + item.name + '</td>' +
                    '<td>' + item.email + '</td>' +
                    '</tr>';
            });
            $('#data-table tbody').html(rows);
        }

        function exportTableToCSV() {
            var csvData = [];
            var rows = $('#data-table tr');

            // 表头
            var headers = [];
            $(rows[0]).find('th').each(function(){
                headers.push($(this).text());
            });
            csvData.push(headers.join(','));

            // 表格数据
            rows.each(function(index){
                if(index === 0) return; // 跳过表头行
                var cols = [];
                $(this).find('td').each(function(){
                    cols.push($(this).text());
                });
                csvData.push(cols.join(','));
            });

            // 创建隐藏的可下载链接
            var csvContent = "data:text/csv;charset=utf-8," 
                            + csvData.join("\n");
            var encodedUri = encodeURI(csvContent);
            var link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "table_data.csv");
            document.body.appendChild(link); // 这句是为了Firefox
            link.click(); // 自动点击下载
        }
    </script>
</body>

</html>